package com.scm.biz.action;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.Factory;
import com.scm.biz.dao.FactoryDao;
import com.scm.biz.dto.FactoryDto;
import com.scm.biz.enums.FileCategoryEnum;
import com.scm.biz.query.FactoryQuery;
import com.scm.biz.result.FactoryResult;
import com.scm.biz.service.FactoryService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.core.bean.resp.RespBean;
import com.scm.utils.Const;
import com.scm.utils.UploadAndDownUtil;

@Controller
@RequestMapping("/factory")
public class FactoryAction {

	@Resource
	private FactoryService factoryService;
	@Resource
	private FactoryDao factoryDao;

	public FactoryAction() {

	}

	/**
	 * 展示工厂列表
	 * @param fq 查询条件(只需传入页码)
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView selectFactoryList(FactoryQuery fq,HttpServletRequest req) {
		//如果合作条件值为0，则表示该查询条件为空
		if("0".equals(fq.getCooperationCondition())){
			fq.setCooperationCondition(null);
		}
		//如果工厂人数值为0，则表示该查询条件为空
		if("0".equals(fq.getPersonAmount())){
			fq.setPersonAmount(null);
		}
		if(fq.getAddress()!=null&&!fq.getAddress().isEmpty()){
			String[] areaList = fq.getAddress().split(",");
			//输入省市区
			if(areaList.length==3){
				fq.setProvince(areaList[0]);
				fq.setCity(areaList[1]);
				fq.setArea(areaList[2]);
			}
			//输入省市
			if(areaList.length==2){
				fq.setProvince(areaList[0]);
				fq.setCity(areaList[1]);
			}
			//输入省
			if(areaList.length==1){
				fq.setProvince(areaList[0]);
			}
		}
		//如果页码没输入，则默认显示第1页
		if (fq.getPageNo() == 0) {
			fq.setPageNo(1);
		}
		fq.setRecourdCount(factoryService.getTotal(fq));
		ModelAndView mv = new ModelAndView("factory/factory_list");
		List<FactoryResult> factoryResults = factoryService.getFactoryList(fq);
		mv.addObject("factoryDtos", factoryResults);
		mv.addObject("splitPage", fq.getSplitPage());
		mv.addObject("name", fq.getName());
		mv.addObject("linkman",fq.getLinkman());
		mv.addObject("cooperationCondition",fq.getCooperationCondition());
		mv.addObject("personAmount",fq.getPersonAmount());
		mv.addObject("address", fq.getAddress());
		mv.addObject("province", fq.getProvince());
		mv.addObject("city", fq.getCity());
		mv.addObject("area",fq.getArea());
		mv.addObject("url", Const.getPath(req));
		return mv;
	}

	/**
	 * 根据指定查询字段检索符合要求的工厂列表
	 * 
	 * @param fq
	 *            查询条件（包含指定查询条件和页码）
	 * @return
	 */
	@RequestMapping("/listQuery")
	public ModelAndView selectFactoryListQuery(FactoryQuery fq) {
		if (fq.getPageNo() == 0) {
			fq.setPageNo(1);
		}
		ModelAndView mv = new ModelAndView("factory/factory_list");
		List<FactoryResult> factoryResults = factoryService.getFactoryList(fq);
		mv.addObject("factoryDtos", factoryResults);
		mv.addObject("splitPage", fq.getSplitPage());
		return mv;
	}

	@RequestMapping("/showDetailPage")
	public ModelAndView showFactoryDetail(String factoryId) {
		ModelAndView mv = new ModelAndView("factory/factory_details");
		FactoryResult factoryResult = factoryService.getFactoryDetailById(Long.valueOf(factoryId));
		mv.addObject("factoryDetail", factoryResult);
		// 拼接后的工厂地址
		String factoryAddress = "";
		if (factoryResult.getProvince() != null) {
			factoryAddress += factoryResult.getProvince();
		}
		if (factoryResult.getCity() != null) {
			factoryAddress += factoryResult.getCity();
		}
		if (factoryResult.getArea() != null) {
			factoryAddress += factoryResult.getArea();
		}
		factoryAddress += factoryResult.getDetail_address();
		mv.addObject("factoryAddress", factoryAddress);
		return mv;
	}

	@RequestMapping("/detail")
	@ResponseBody
	public RespBean<FactoryResult> getDetail(String factoryId) {
		RespBean<FactoryResult> respBean = new RespBean<FactoryResult>();
		FactoryResult factoryResult = factoryService.getFactoryDetailById(Long.valueOf(factoryId));
		respBean.setBody(factoryResult);
		return respBean;
	}

	/**
	 * 插入工厂数据
	 * @param factoryDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertFactory")
	@ResponseBody
	public RespBean<String> insertFactory(FactoryDto factoryDto) throws Exception {
		// 前台输入数据合法性检测检测检测
		if (factoryDto.getFactoryName() == null || factoryDto.getFactoryName().isEmpty()) {
			throw new UfdmException("工厂名不能为空");
		}
		//工厂名是否存在
		boolean res = factoryService.haveName(factoryDto.getFactoryName(), factoryDto.getId());
		if(!res){
			throw new UfdmException("工厂名已存在");
		}
		if (factoryDto.getProvinceId() == null || factoryDto.getProvinceId() == 0) {
			throw new UfdmException("省地址不能为空");
		}
		if (factoryDto.getCityId() == null || factoryDto.getCityId() == 0) {
			throw new UfdmException("市地址不能为空");
		}
		if (factoryDto.getAreaId() == null || factoryDto.getAreaId() == 0) {
			throw new UfdmException("区县地址不能为空");
		}
		if (factoryDto.getContact() == null || factoryDto.getContact().isEmpty()) {
			throw new UfdmException("联系方式不能为空");
		}
		if(!factoryDto.getContact().matches(Const.CONTACT)){
			throw new UfdmException("联系方式规则不合法");
		}
		if (factoryDto.getLinkman() == null || factoryDto.getLinkman().isEmpty()) {
			throw new UfdmException("联系人不能为空");
		}
		if (factoryDto.getDetailAddress() == null || factoryDto.getDetailAddress().isEmpty()) {
			throw new UfdmException("详细地址不能为空");
		}
		if (factoryDto.getPersonAmount() == null || factoryDto.getPersonAmount().isEmpty()) {
			throw new UfdmException("工厂人数不能为空");
		}
		if (factoryDto.getTattingStyleIds() == null || factoryDto.getTattingStyleIds().length == 0) {
			throw new UfdmException("梳织类型不能为空");
		}
		if (factoryDto.getWovenStyleIds() == null || factoryDto.getWovenStyleIds().length == 0) {
			throw new UfdmException("针织类型不能为空");
		}
		if (factoryDto.getSweaterStyleIds() == null || factoryDto.getSweaterStyleIds().length == 0) {
			throw new UfdmException("毛衣类型不能为空");
		}
		if (factoryDto.getSaleTarget() == null || factoryDto.getSaleTarget().isEmpty()) {
			throw new UfdmException("销往目的地不能为空");
		}
		if (factoryDto.getCooperationCondition() == null || factoryDto.getCooperationCondition().isEmpty()) {
			throw new UfdmException("合作条件不能为空");
		}
		if(factoryDto.getEstimateReport()==null||factoryDto.getEstimateReport().isEmpty()){
			throw new UfdmException("评估报告不能为空");
		}
		RespBean<String> respBean = new RespBean<>();
		factoryService.insertFactory(factoryDto);
		respBean.setBody("新建工厂成功");
		return respBean;
	}

	/**
	 * 展示新增工厂页面
	 * 
	 * @return
	 */
	@RequestMapping("/showAddPage")
	public ModelAndView showAddPage() {
		return new ModelAndView("factory/factory_add");
	}

	/**
	 * 删除工厂信息
	 * 
	 * @param factoryId
	 *            要删除的工厂Id
	 * @return
	 */
	@RequestMapping("/deleteFactory")
	@ResponseBody
	public RespBean<String> deleteFactory(String factoryId) {
		RespBean<String> respBean = new RespBean<String>();
		boolean haveFactory = factoryService.haveOrder(Integer.parseInt(factoryId));
		if(haveFactory){
			respBean.setBody("该工厂有订单记录，不能删除");
			return respBean;
		}
		boolean b = factoryService.deleteFactoryById(Long.valueOf(factoryId));
		if (b == true) {
			respBean.setBody("删除成功");
			return respBean;
		}
		respBean.setBody("删除失败");
		return respBean;
	}

	/**
	 * 展示修改工厂页面
	 * @param factoryId
	 * @return
	 */
	@RequestMapping("/showModifyPage")
	public ModelAndView showModifyFactory(Integer factoryId) {
		ModelAndView mv = new ModelAndView("factory/factory_modify");
		mv.addObject("factoryId", factoryId);
		return mv;
	}

	/**
	 * 修改工厂信息
	 * @param factoryDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateFactory")
	@ResponseBody
	public RespBean<String> updateFactory(FactoryDto factoryDto) throws Exception {
		// 前台输入数据合法性检测检测检测
		if (factoryDto.getFactoryName() == null || factoryDto.getFactoryName().isEmpty()) {
			throw new UfdmException("工厂名不能为空");
		}
		//工厂名是否存在
		boolean res = factoryService.haveName(factoryDto.getFactoryName(), factoryDto.getId());
		if(!res){
			throw new UfdmException("工厂名已存在");
		}
		if (factoryDto.getProvinceId() == null || factoryDto.getProvinceId() == 0) {
			throw new UfdmException("省地址不能为空");
		}
		if (factoryDto.getCityId() == null || factoryDto.getCityId() == 0) {
			throw new UfdmException("市地址不能为空");
		}
		if (factoryDto.getAreaId() == null || factoryDto.getAreaId() == 0) {
			throw new UfdmException("区县地址不能为空");
		}
		if (factoryDto.getContact() == null || factoryDto.getContact().isEmpty()) {
			throw new UfdmException("联系方式不能为空");
		}
		if(!factoryDto.getContact().matches(Const.CONTACT)){
			throw new UfdmException("联系方式规则不合法");
		}
		if (factoryDto.getLinkman() == null || factoryDto.getLinkman().isEmpty()) {
			throw new UfdmException("联系人不能为空");
		}
		if (factoryDto.getDetailAddress() == null || factoryDto.getDetailAddress().isEmpty()) {
			throw new UfdmException("详细地址不能为空");
		}
		if (factoryDto.getPersonAmount() == null || factoryDto.getPersonAmount().isEmpty()) {
			throw new UfdmException("工厂人数不能为空");
		}
		if (factoryDto.getTattingStyleIds() == null || factoryDto.getTattingStyleIds().length == 0) {
			throw new UfdmException("梳织类型不能为空");
		}
		if (factoryDto.getWovenStyleIds() == null || factoryDto.getWovenStyleIds().length == 0) {
			throw new UfdmException("针织类型不能为空");
		}
		if (factoryDto.getSweaterStyleIds() == null || factoryDto.getSweaterStyleIds().length == 0) {
			throw new UfdmException("毛衣类型不能为空");
		}
		if (factoryDto.getSaleTarget() == null || factoryDto.getSaleTarget().isEmpty()) {
			throw new UfdmException("销往目的地不能为空");
		}
		if (factoryDto.getCooperationCondition() == null || factoryDto.getCooperationCondition().isEmpty()) {
			throw new UfdmException("合作条件不能为空");
		}
		RespBean<String> respBean = new RespBean<String>();
		boolean b = factoryService.updateFactoryById(factoryDto);
		if (b == true) {
			respBean.setBody("修改成功");
			return respBean;
		}
		respBean.setBody("修改失败");
		return respBean;
	}

	/**
	 * 上传工厂评估文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadReport")
	@ResponseBody
	public RespBean<String> uploadReport(MultipartFile estimateReport, Integer factoryId) throws Exception {
		RespBean<String> respBean = new RespBean<String>();
		if (estimateReport != null && !estimateReport.isEmpty()) {
			String filePath = UploadAndDownUtil.uploadFile(estimateReport,FileCategoryEnum.FACTORY_REPORT.value());
			Factory factory = new Factory();
			String originName = estimateReport.getOriginalFilename();
			factory.setId((long) factoryId);
			factory.setEstimate_report(filePath);
			factory.setOrigin_name(originName);
			factoryService.updateEstimateReport(factory);
			respBean.setBody("上传成功");
			return respBean;
		}
		respBean.setBody("工厂报告不能为空");
		return respBean;
	}

	/**
	 * 下载工厂评估文件
	 * 
	 * @param fileName
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/downloadReport")
	@ResponseBody
	public String downloadReport(String fileName, HttpServletRequest request, HttpServletResponse response)throws Exception {
		String originName = factoryService.selectOriginName(fileName);
		UploadAndDownUtil.downFile(originName,fileName,request,response);
		return null;
	}
	
	@RequestMapping("/haveName")
	@ResponseBody
	public RespBean<String> havaName(String name,Long id) throws Exception{
		RespBean<String> respBean = new RespBean<String>();
		boolean res = factoryService.haveName(name, id);
		if(!res){
			throw new UfdmException("工厂名已存在");
		}
		respBean.setBody("工厂名不存在");
		return respBean;
	}
	
}
